package com.jieyun.rbac.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jieyun.core.component.page.Page;
import com.jieyun.core.component.page.Pager;
import com.jieyun.core.utils.ServerResponse;
import com.jieyun.rbac.dto.SysDictDTO;
import com.jieyun.rbac.mapper.SysDictMapper;
import com.jieyun.rbac.po.SysDict;
import com.jieyun.rbac.service.SysDictService;

/**
 * 系统数据字典服务
 * @author trek
 */
@Service
public class SysDictServiceImpl implements SysDictService {

	@Resource
	private SysDictMapper sysDictMapper;
	
	/*
	 * (non-Javadoc)
	 * @see com.jieyun.rbac.service.SysDictService#dictList()
	 */
	@Override
	@Page
	public Pager<SysDictDTO> dictList() {
		return Pager.adapt(this.sysDictMapper.dictList());
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.jieyun.rbac.service.SysDictService#dictDelete(java.lang.Integer)
	 */
	@Override
	public ServerResponse dictDelete(Integer id) {
		
		if(id == null) {
			return  ServerResponse.fail("删除的字典不存在");
		}
		
		int count = this.sysDictMapper.deleteById(id);
		if(count == 0) {
			return ServerResponse.fail("删除字典失败");
		}
		
		return ServerResponse.ok("删除字典成功");
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.jieyun.rbac.service.SysDictService#dictUpdate(com.jieyun.rbac.dto.SysDictDTO)
	 */
	@Override
	public ServerResponse dictUpdate(SysDictDTO dict) {
		if(dict ==null) {
			return ServerResponse.fail("删除的字典不存在");
		}
		
		if(dict.getId() == null) {
			return ServerResponse.fail("更新没有传入字典的id");
		}
		
		SysDict sysDict = new SysDict();
		BeanUtils.copyProperties(dict, sysDict);
		
		int count = this.sysDictMapper.updateById(sysDict);
		if(count == 0) {
			return ServerResponse.fail("删除字典失败");
		}
		
		return ServerResponse.ok("删除字典成功");
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.jieyun.rbac.service.SysDictService#dictAdd(com.jieyun.rbac.param.SysDictParam)
	 */
	@Override
	public ServerResponse dictAdd(SysDict dict) {
		
		if(dict == null) {
			return ServerResponse.fail("新增的字典不能为空");
		}
		
		if(dict.getDictType() == null) {
			return ServerResponse.fail("没有传入字典的类型");
		}
		
		int count = this.sysDictMapper.selectCount(new EntityWrapper<>(SysDict.builder().dictType(dict.getDictType()).dictKey(dict.getDictKey()).build()));
		
		if(count != 0) {
			return ServerResponse.fail("在该字典组之中存在相同键的字典映射");
		}
		
		count = this.sysDictMapper.insert(dict);
		
		if(count == 0) {
			return ServerResponse.fail("添加字典失败");
		}
		
		return ServerResponse.ok("添加字典成功");
	}
	
	
	
	
}
